// Copyright (c) 2008 Matthew Johnson
// Licensed under the MIT License (see license.txt)
package actionml.geom {
	import actionml.Global;
	
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class RectangleMethods {
		public static function initialize() {
			Global.initializeExtension(PointMethods, Point);
			Global.initializeExtension(RectangleAccessorMethods, Rectangle);
			Global.initializeExtension(RectangleMethods, Rectangle);
		}
		public static var instanceMethods:Object = {			
			getIntersectsLeft: function(r:Rectangle) {
				var i:Rectangle = this.intersection(r);
				return i.getLeft() == this.getLeft() && i.width != 0;
			},
			getIntersectsRight: function(r:Rectangle) {
				var i:Rectangle = this.intersection(r);
				return i.getRight() == this.getRight() && i.width != 0;
			},
			getIntersectsTop: function(r:Rectangle) {
				var i:Rectangle = this.intersection(r);
				return i.getTop() == this.getTop() && i.height != 0;
			},
			getIntersectsBottom: function(r:Rectangle) {
				var i:Rectangle = this.intersection(r);
				return i.getBottom() == this.getBottom() && i.height != 0;
			},
			
			getAdjustmentNecessaryToContainRect: function(r:Rectangle) {
				var p:Point = new Point(0, 0);
				if (r.getRight() > this.getRight()) {
					p.x = this.getRight() - r.getRight();
				}
				if (r.getBottom() > this.getBottom()) {
					p.y = this.getBottom() - r.getBottom()
				}
				// top and left adjustments are done last so the
				// rect is top and / or left aligned if it is too big to fit
				// within the containing rect
				if (r.getLeft() < this.getLeft()) {
					p.x = this.getLeft() - r.getLeft();
				}
				if (r.getTop() < this.getTop()) {
					p.y = this.getTop() - r.getTop();
				}
				return p;
			},
			getDistanceToEdgeAtAngle: function(radians:Number) {
				var adjacent:Number;
				radians = radians.normalizeRadiansToQuadrant();
				var cornerAngle:Number = Math.atan2(this.height/2, this.width/2);
				if (radians > cornerAngle) {	
					adjacent = this.height/2;
					// we flip the angle since we are using the y axis now
					radians = (Math.PI / 2) - radians;
				} else {
					adjacent = this.width/2;
				}
 				return adjacent/Math.cos(radians);
			},
			// angles are clockwise
			getEdgeIntersectionAtAngle: function(radians:Number) {
				return this.getCenter().addRadians(this.getDistanceToEdgeAtAngle(radians), radians);
			}
		};
	}
}